import React, { useState,useEffect,useRef } from "react";
import {Button, Badge, Dropdown, Col, Card, Layout, Modal, Image, List, message, Row, Select} from "antd";
import { Link, history } from '@umijs/max';
import {
    VideoCameraFilled,
    EditFilled,
    VerticalAlignTopOutlined,
    DeleteOutlined,
    VerticalAlignBottomOutlined
} from '@ant-design/icons';
import {getLoginUserUsingGet} from "@/services/openAPI-backend/userController";
import {
    articleListUsingGet, cancelTopUsingPost,
    deleteArticleUsingPost,
    hotArticleListUsingGet,
    listAllArticleUsingGet,
    topArticleUsingPost
} from "@/services/openAPI-backend/articleController";
import {PageContainer} from "@ant-design/pro-components";
import {getAllCategoryListUsingGet} from "@/services/openAPI-backend/categoryController";
import {keyframes} from "antd-style";
import {sleep} from "qiankun/es/utils";
const ChatInterface: React.FC = () => {
    const Header = () => {

}
    const fadeAndScaleIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
      `;
    const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateY(100%); /* 初始位置在屏幕下方100% */
        }
        to {
            opacity: 1;
            transform: translateY(0); /* 结束位置在正常位置 */
        }
`;
    const [loading, setLoading] = useState(false);
    const [list, setList] = useState<API.PageVo[]>();
    const [total, setTotal] = useState<number>();
    const [categoryList, setCategoryList] = useState<API.CategoryVo[]>([]);
    const [hotArticleList, setHotArticleList] = useState<API.ArticleVo[]>([]);
    const [currentUser, setCurrentUser] = useState<API.UserVo>();
    const [selectedValue, setSelectedValue] = useState();
    let selectCata = 0;
    const selectRef = useRef(null);
    const showDeleteConfirm = (id:number) => {
        Modal.confirm({
            title: '确认删除',
            content: '是否确认删除该文章？',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {handleDelete(id)
            },
        });
    };
    const getLoginUser = async () => {
        try {

            const res = await getLoginUserUsingGet();
            if (res?.data)
                setCurrentUser(res?.data);
        }catch (e){
            history.push('/user/login');
        }
    };
    const loadHotArticleList = async () => {
        const res = await hotArticleListUsingGet({
        });
        if (res?.data) {
            setHotArticleList(res?.data);
        }
    }
    const loadCategoryList = async () => {
        const res = await getAllCategoryListUsingGet();
        if (res?.data) {
            setCategoryList(res?.data);
        }
    };
    const onChange = (value: number) => {
        console.log(`selected ${value}`);
        selectCata = value;
        console.log(selectCata);
        loadData();

    };
    const handleDelete = async (id:number) => {
        try {
            const res = await deleteArticleUsingPost({
                id:id
            })
              if(res.data){
                  message.success("删除成功");
                  loadData();
              }else {
                  message.error("删除失败");
              }

        }
        catch (e){
            message.error("删除失败");
        }
    };
    const retrunAll = async () => {
        selectCata = 0;
        loadData();
        setSelectedValue(null)
    }
    const toTop = async (id:number) => {
         try {
             const res = await topArticleUsingPost({
                 id:id
             })
             if(res.data){
                 message.success("置顶成功");
                 loadData();
             }else {
                 message.error("置顶失败");
             }
         }catch (e){
             message.error("置顶失败");
         }
    }
    const onSearch = (value: string) => {
        console.log('search:', value);
    };
    const cancelTop = async (id:number) =>{
        try {
            const res = await cancelTopUsingPost({
                id:id
            })
            if(res.data){
                message.success("取消置顶成功");
                loadData();
            }else {
                message.error("取消置顶失败");
            }
        }catch (e){
            message.error("取消置顶失败");
        }
    }
    const loadData = async (pageNum: number = 1, pageSize: number = 10) => {
        setLoading(true);
        try {
            const res = await articleListUsingGet({
                pageNum,
                pageSize,
                categoryId:selectCata==0?"":selectCata,
            });
            setList(res?.data?.rows ?? []);
            console.log(list);
            setTotal(res.data?.total ?? 0);
        } catch (error) {
            message.error("加载失败，请重试'");
        }
        setLoading(false);
    };
    useEffect(() => {
        loadData();
        loadCategoryList();
        loadHotArticleList();
        getLoginUser();
    }, []);
 return (
     <PageContainer style={{overflow: 'auto'}} extra={ <div style={{marginRight: '530px'}}><Select
         ref={selectRef}
         showSearch
         placeholder="Select a label"
         optionFilterProp="label"
         value={selectedValue}
         onChange={onChange}
         onSearch={onSearch}
         options={categoryList.map((item) => ({
             label: item.name,
             value: item.id,
         }))}
     /><Button style={{marginLeft: '10px'}} onClick={()=>{retrunAll()}}>返回全部</Button></div> }>
     <List  className="Forum-List"
            loading={loading}
            itemLayout="vertical"
            dataSource={list}
            size="large"
            style={{marginLeft: '10px', animation: `${fadeAndScaleIn} 2s ease-in-out`}}
            renderItem={(item, index) => {
                const apiLink = `/forum/${item.id}`
                return(
                    <Badge.Ribbon text={<p style={{color: '#ffffff',fontWeight: 'bold',display: 'flex', justifyContent: 'center', alignItems: 'center',marginTop:"3px"}}>{item.categoryName}</p>} style={{marginTop: '100px',height: '30px',width: '80px',animation: `${fadeIn} 1s ease-in-out`}} placement={'start'} color='#1677ff'>
                        <Card extra = {currentUser?.userRole =="admin"?<div><Button style={{marginRight: '5px'}} icon={<DeleteOutlined />} onClick={()=>{showDeleteConfirm(item.id)}} /><Button icon={item?.isTop==1?<VerticalAlignBottomOutlined />:<VerticalAlignTopOutlined />} onClick={()=>{item?.isTop==1?cancelTop(item?.id):toTop(item?.id)}} /></div>:''} style={{marginBottom: '6px',width: '65%',animation: `${fadeIn} 1s ease-in-out`}} hoverable={true} key={index}>
                            <div
                                style={{
                                    position: 'absolute', // 使用绝对定位
                                    top: '-15px', // 调整距离顶部的位置
                                    left: '-15px', // 调整距离左侧的位置
                                    backgroundColor: '#1677ff', // 根据需要设置背景颜色
                                    borderRadius: '50%', // 制作圆形
                                    padding: '4px 8px', // 内边距
                                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)', // 可选的阴影效果
                                }}
                            >
                                <div style={{marginTop: "5px",padding:0,marginBottom: '0',color: '#ffffff',display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                                {item?.createTime.split("-")[1].split("")[1]}月
                                </div>
                                <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center',padding:0,marginTop:-10,marginBottom:'5px'}}>
                                    <p style={{fontSize: '20px',color: '#ffffff',fontWeight: 'bold',marginTop: 0,marginBottom: '0',padding:0,marginLeft: '12px',marginRight: '12px'}}>{item?.createTime.split("-")[2].split(" ")[0]}</p>
                                </div>
                            </div>
                            <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                                <h2 style={{fontWeight: 'bold'}}>{item?.title}</h2>
                            </div>
                            <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                                <EditFilled/><div style={{marginLeft: '6px',}}>发表于：</div><a style={{
                                color: 'black',
                                marginRight: '10px'
                            }}>{item?.createTime.split(" ")[0]}</a><VideoCameraFilled/><a
                                style={{marginRight: '6px'}}></a>{item?.viewCount}次观看
                            </div>
                            <p style={{marginTop: '15px', marginLeft: '150px'}}>{item?.summary}</p>
                            <div style={{
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                marginTop: '5px'
                            }}>
                                <Image style={{width: '100%'}} preview={false} src={item?.thumbnail}></Image>
                            </div>
                            <div style={{
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                marginTop: '10px'
                            }}>
                                <Button ghost={true} type={"link"} onClick={()=>{history.push(apiLink)}}>阅读全文</Button>
                            </div>

                        </Card>
                    </Badge.Ribbon>
                );
            }}></List>
     <Card title={<div style={{fontWeight: 'bold'}}> 热门文章</div>} style={{width: '20%',position:"fixed",right:"8%",top:"11.5%",height:'30%',overflow:'auto',maxHeight:'30%',animation: `${fadeAndScaleIn} 1.5s ease-in-out`,}}>
         <List
             className="Forum-List"
             loading={loading}
             itemLayout="vertical"
             dataSource={hotArticleList}
             size="small"
             renderItem={(item, index) => {
                 return (
                     <div style={{marginBottom: '10px'}}><a href={`/forum/${item.id}`} style={{
                         fontWeight: 'bold',
                         fontSize: '17px',
                         color: 'black',
                         marginBottom: '10px'

                     }}>{item.title}<a style={{
                         marginLeft: '10px',
                         color: 'black',
                         fontWeight: 'normal'
                     }}> - {item.viewCount}次观看<br/></a></a></div>
                 );
             }
             }
         ></List>
     </Card>
     </PageContainer>
 );
};

export default ChatInterface;
